package com.eastfair.builder.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.eastfair.auth.api.AuthServiceFeign;
import com.eastfair.auth.api.GlobalBusinessServiceFeign;
import com.eastfair.auth.api.RoleServiceFeign;
import com.eastfair.auth.api.UserAccountServiceFeign;
import com.eastfair.auth.dto.*;
import com.eastfair.auth.entity.Role;
import com.eastfair.auth.enumeration.OrganizationOrgTypeEnum;
import com.eastfair.auth.enumeration.OrganizationVestTypeEnum;
import com.eastfair.auth.enumeration.RoleRoleTypeEnum;
import com.eastfair.auth.exceptioncode.AuthServiceExceptionCode;
import com.eastfair.auth.vo.RoleVo;
import com.eastfair.auth.vo.UserAccountVo;
import com.eastfair.builder.dto.BindBuilderServiceProviderRoleDTO;
import com.eastfair.builder.dto.RemoveBuilderServiceProviderRoleDTO;
import com.eastfair.builder.exceptioncode.BuilderExceptionCode;
import com.eastfair.builder.service.BuilderRegisterService;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.home.vo.HomeRegisterDataVO;
import com.eastfair.jwt.service.JwtService;
import com.eastfair.matching.service.AuthMatchRoleService;
import com.eastfair.matching.service.AuthMatchUserRoleService;
import com.eastfair.venuebooking.api.ServiceProviderFeign;
import com.eastfair.venueservice.enumeration.ServiceProviderRoleEnum;
import com.eastfair.venueservice.enumeration.ServiceProviderTypeEnum;
import com.eastfair.venueservice.vo.ServiceProviderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 业务实现类
 * 服务项
 * </p>
 *
 * @author lyw
 * @date 2022-08-10
 */
@Slf4j
@Service
public class BuilderRegisterServiceImpl implements BuilderRegisterService {
    @Autowired
    private UserAccountServiceFeign userAccountServiceFeign;
    @Autowired
    private AuthServiceFeign authServiceFeign;
    @Autowired
    private RoleServiceFeign roleServiceFeign;
    @Autowired
    private GlobalBusinessServiceFeign globalBusinessServiceFeign;
    @Autowired
    JwtService jwtService;
    @Autowired
    private ServiceProviderFeign serviceProviderFeign;
    @Resource
    private AuthMatchRoleService roleService;

    @Resource
    private AuthMatchUserRoleService userRoleService;

    /**
     * 搭建商服务商注册
     *
     * @param userAccountDto
     * @return
     */
    @Override
    public HomeRegisterDataVO registerBuilderUser(UserAccountDto userAccountDto) {
        log.info("BuilderRegisterServiceImpl +++++ registerBuilderUser -搭建商服务商注册 params={}", JSONObject.toJSON(userAccountDto));
        R<UserAccountVo> r = userAccountServiceFeign.registerSubSystemUser(userAccountDto);
        if (!r.getIsSuccess()) {
            throw BizException.wrap(r.getCode(), r.getMsg());
        }
        //查询搭建商服务商信息
        R<ServiceProviderVO> serviceProviderVOR = serviceProviderFeign.getByUserId(r.getData().getId(), ServiceProviderTypeEnum.BUILD_SERVICE_PROVIDER.getCode());        //token解析对象
        if (!serviceProviderVOR.getIsSuccess()) {
            throw BizException.wrap(serviceProviderVOR.getCode(), serviceProviderVOR.getMsg());
        }
        return HomeRegisterDataVO.builder().userAccountVo(r.getData()).serviceProviderVO(serviceProviderVOR.getData()).build();
    }

    /**
     * 搭建商用户附常规角色
     *
     * @param bindBuilderServiceProviderRoleDTO
     * @return
     */
    @Override
    public Boolean bindBuilderServiceProviderRole(BindBuilderServiceProviderRoleDTO bindBuilderServiceProviderRoleDTO) {
//        log.info("BuilderRegisterServiceImpl +++++ bindBuilderServiceProviderRole -搭建商服务商注册 params={}", JSONObject.toJSON(bindBuilderServiceProviderRoleDTO));
//        //查询基础角色信息
//        RoleDTO roleDTO = new RoleDTO();
////        roleDTO.setBusinessTag(bindBuilderServiceProviderRoleDTO.getServiceProviderRole());
//        roleDTO.setRoleType(RoleRoleTypeEnum.P_COMPOSITE_PRODUCER_ADMIN);
//
//        R<List<RoleVo>> queryRole = roleServiceFeign.queryRole(roleDTO);
//        if (!queryRole.getIsSuccess()) {
//            throw BizException.wrap(queryRole.getCode(), queryRole.getMsg());
//        }
//        //判断角色菜单不能为空
//        if (Objects.isNull(queryRole) || CollectionUtils.isEmpty(queryRole.getData()) || CollectionUtils.isEmpty(queryRole.getData().get(0).getMenuIds())) {
//            throw BizException.wrap(BuilderExceptionCode.NOT_ROLE_MENU_NULL);
//        }
//
//        ContextUtil.setTeamId(bindBuilderServiceProviderRoleDTO.getServiceProviderId());
//
//        R<ServiceProviderVO> r = serviceProviderFeign.getById(bindBuilderServiceProviderRoleDTO.getServiceProviderId());
//        if (!r.getIsSuccess()) {
//            throw BizException.wrap(r.getCode(), r.getMsg());
//        }
//
//        //创建顶级组织
//        OrganizationDTO organizationDTO = new OrganizationDTO();
//        //组织类型  搭建商
//        organizationDTO.setOrgType(OrganizationOrgTypeEnum.P_COMPOSITE_PRODUCER);
//        //资源
//        organizationDTO.setVestType(OrganizationVestTypeEnum.R);
//        //公司名称
//        organizationDTO.setName(r.getData().getCompanyName());
//        R orgR = authServiceFeign.createOrgGroup(organizationDTO);
//
//
//
//        //创建用户角色
//        RoleDTO role = new RoleDTO();
//        role.setName(ServiceProviderRoleEnum.BUILD_COMMON_ROLE.getDesc());
//        role.setMenuIds(queryRole.getData().get(0).getMenuIds());
//        role.setBusinessTag(bindBuilderServiceProviderRoleDTO.getServiceProviderRole());
//        //绑定原始角色
//        role.setSourceRoleId(queryRole.getData().get(0).getId());
//        R<Role> roleR = roleServiceFeign.createRole(role);
//
//        Long roleId = null;
//        if (roleR.getIsSuccess()) {
//            roleId = roleR.getData().getId();
//        } else {
//            if (AuthServiceExceptionCode.ROLE_AGAIN.getCode() == roleR.getCode()) {
//                //角色已存在,查询角色
//                R<List<RoleVo>> listR = roleServiceFeign.queryRole(role);
//                if (listR.getIsSuccess() && CollectionUtils.isNotEmpty(listR.getData())) {
//                    roleId = listR.getData().get(0).getId();
//                }
//            } else {
//                throw BizException.wrap(roleR.getCode(), roleR.getMsg());
//            }
//        }
//
//        //角色id集合
//        List<Long> roleIds = Lists.newArrayList();
//        roleIds.add(roleId);
//        List<Long> userIds = Lists.newArrayList();
//        userIds.add(bindBuilderServiceProviderRoleDTO.getUserId());
//        UserRoleDto userRoleDto = new UserRoleDto();
//        userRoleDto.setRoleIds(roleIds);
//        userRoleDto.setUserIds(userIds);
//        //给用户添加基础角色
//        R userRole = authServiceFeign.addUserRole(userRoleDto);
//        if (!userRole.getIsSuccess()) {
//            throw BizException.wrap(userRole.getCode(), userRole.getMsg());
//        }
//
//        //修改关联信息
//        UserAccountDto accountDto = new UserAccountDto();
//        accountDto.setId(bindBuilderServiceProviderRoleDTO.getUserId());
//        accountDto.setProducerId(bindBuilderServiceProviderRoleDTO.getServiceProviderId());
//        R<Boolean> userAccountR = userAccountServiceFeign.updateCorrelationById(accountDto);
//        if (!userAccountR.getIsSuccess()) {
//            throw BizException.wrap(userAccountR.getCode(), userAccountR.getMsg());
//        }
//
//        return Boolean.TRUE;








        /*
        入参例子
        {
            "roleDTO": {
                "roleType": "P_COMPOSITE_PRODUCER_ADMIN",
                "name": "搭建商常规角色",
                "businessTag": "test"
            },
            "organizationDTO": {
                "orgType":"P_COMPOSITE_PRODUCER",
                "vestType":"R",
                "name":"北京公司43432"
            },
            "teamId": "2542558554963316736",
            "userAccountDto": {
                "id":"2542555531319447552",
                "producerId":"2542558554963316736"
            }
        }
*/


        RegisterDTO registerDTO = new RegisterDTO();
        log.info("BuilderRegisterServiceImpl +++++ bindBuilderServiceProviderRole -搭建商服务商注册 params={}", JSONObject.toJSON(bindBuilderServiceProviderRoleDTO));
        //创建顶级组织
        OrganizationDTO organizationDTO = new OrganizationDTO();
        //组织类型  搭建商
        organizationDTO.setOrgType(OrganizationOrgTypeEnum.P_COMPOSITE_PRODUCER);
        //资源
        organizationDTO.setVestType(OrganizationVestTypeEnum.R);
        organizationDTO.setParentId(BusinessConstant.parentId);
        //公司名称
        R<ServiceProviderVO> r = serviceProviderFeign.getById(bindBuilderServiceProviderRoleDTO.getServiceProviderId());
        if (!r.getIsSuccess()) {
            throw BizException.wrap(r.getCode(), r.getMsg());
        }
        organizationDTO.setName(r.getData().getCompanyName());
        registerDTO.setOrganizationDTO(organizationDTO);
        //创建用户角色
        RoleDTO role = new RoleDTO();
        role.setRoleType(RoleRoleTypeEnum.P_COMPOSITE_PRODUCER_ADMIN);
        role.setName(ServiceProviderRoleEnum.BUILD_COMMON_ROLE.getDesc());
        role.setBusinessTag(bindBuilderServiceProviderRoleDTO.getServiceProviderRole());
        registerDTO.setRoleDTO(role);
        //修改关联信息
        UserAccountDto accountDto = new UserAccountDto();
        accountDto.setId(bindBuilderServiceProviderRoleDTO.getUserId());
        //搭建商id
        accountDto.setProducerId(bindBuilderServiceProviderRoleDTO.getServiceProviderId());
        registerDTO.setUserAccountDto(accountDto);
        registerDTO.setTeamId(bindBuilderServiceProviderRoleDTO.getServiceProviderId());
        log.info("registerDTO is {}", JSONObject.toJSONString(registerDTO));
        userAccountServiceFeign.registerServiceProvider(registerDTO);

        return Boolean.TRUE;
    }


    /**
     * 搭建商服务商移除角色
     *
     * @param removeBuilderServiceProviderRoleDTOList
     * @return
     */
    @Override
    public Boolean removeBuilderServiceProviderRole(List<RemoveBuilderServiceProviderRoleDTO> removeBuilderServiceProviderRoleDTOList) {

        if (CollectionUtils.isEmpty(removeBuilderServiceProviderRoleDTOList) || removeBuilderServiceProviderRoleDTOList.size() == 0) {
            throw BizException.wrap(BuilderExceptionCode.NOT_SERVICE_PROVIDER_NULL);
        }
        removeBuilderServiceProviderRoleDTOList.forEach((s) -> {
            ContextUtil.setTeamId(s.getServiceProviderId());
            //查询基础角色信息
            RoleDTO roleDTO = new RoleDTO();
            roleDTO.setBusinessTag(s.getServiceProviderRole());
            R<List<RoleVo>> queryRole = roleServiceFeign.queryRole(roleDTO);
            if (!queryRole.getIsSuccess()) {
                throw BizException.wrap(queryRole.getCode(), queryRole.getMsg());
            }

            //角色id集合
            List<Long> roleIds = Lists.newArrayList();
            List<Long> ids = queryRole.getData().stream().map(RoleVo::getId).collect(Collectors.toList());
            roleIds.addAll(ids);
            List<Long> userIds = Lists.newArrayList();
            userIds.add(s.getUserId());
            UserRoleDto userRoleDto = new UserRoleDto();
            userRoleDto.setRoleIds(roleIds);
            userRoleDto.setUserIds(userIds);
            authServiceFeign.removeOrgRole(userRoleDto);
        });
        return Boolean.TRUE;
    }
}

